package com.scoy.honeymei;


import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.webkit.WebView;

import androidx.annotation.RequiresApi;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.scoy.honeymei.utils.SPHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import cn.jpush.android.api.JPushInterface;
import io.dcloud.adnative.UniAdManager;
import io.dcloud.adnative.model.IPreloadAwardVideoListener;
import okhttp3.OkHttpClient;

/**
 * @ClassName: MeApp$
 * @Description:
 * @Author: GaoZhan
 * @CreateDate: 2019/5/10/0010$ 下午 14:44$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/5/10/0010$ 下午 14:44$
 * @UpdateRemark: 更新内容
 */
public class MeApp extends Application {
    private static MeApp mInstance;

    private static List<Activity> activityList = new ArrayList<Activity>();

    @Override
    public void onCreate() {
        super.onCreate();
        SPHelper.init(this, "honeymei");
        initOkgo();

        //       MultiDex.install(this);

        //获取Context
        context = getApplicationContext();

//        UMConfigure.init(context, "5da6ced93fc1952721000571", "umeng", UMConfigure.DEVICE_TYPE_PHONE, "669c30a9584623e70e8cd01b0381dcb4");
        UMConfigure.preInit(context,"5da6ced93fc1952721000571","umeng");


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            webviewSetPath(this);
        }

        UniAdManager.Config defaultConfig = UniAdManager.obtainDefaultConfig("NA438011E", "121108120311");
        UniAdManager.init(this, defaultConfig);
//        preloadAwardVideo();
    }


    public void finishAllActivity() {
        for (Activity activity : activityList) {
            activity.finish();
        }
    }

    public void add(Activity activity) {
        activityList.add(activity);
    }


    @RequiresApi(api = 28)
    public void webviewSetPath(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(context);

            if (!getApplicationContext().getPackageName().equals(processName)) {//判断不等于默认进程名称
                WebView.setDataDirectorySuffix(processName);
            }
        }
    }

    public String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }

    /**
     * 预加载激励视频的代码示例
     */
    public void preloadAwardVideo(){


        // 预缓存一个激励视频
        UniAdManager.AwardVideoOption awardVideoOption = new UniAdManager.AwardVideoOption();
        awardVideoOption.awardPosId = "1884727747";
        awardVideoOption.adHeight = 1920;
        awardVideoOption.adWidth = 1080;

        UniAdManager.doPreloadAwardVideo(MeApp.this,awardVideoOption,new IPreloadAwardVideoListener(){

            @Override
            public void onError(int code, String message) {
                Log.d("TAG","预缓存激励视频  onError  " + code + " message  --  " + message);
            }

            @Override
            public void onHandleClose() {
                Log.d("TAG","预缓存激励视频  onHandleClose  ");
            }

            @Override
            public void onVideoComplete() {
                Log.d("TAG","预缓存激励视频  onVideoComplete  ");
            }

            @Override
            public void onADClick() {
                Log.d("TAG","预缓存激励视频  onADClick  ");
            }

            @Override
            public void onRewardGet() {
                Log.d("TAG","预缓存激励视频  onRewardGet  ");
            }

            @Override
            public void onADShow() {
                Log.d("TAG","预缓存激励视频  onADShow  ");
            }

            @Override
            public void onSkipVideo() {
                Log.d("TAG","预缓存激励视频  onSkipVideo  ");
            }
        });
    }

    private static Context context;

    //返回
    public static Context getAllContext() {
        return context;
    }

    public static MeApp getInstance() {
        if (mInstance == null) {
            mInstance = new MeApp();
        }
        return mInstance;
    }

    public static void initLate() {
        initJpush();
        initUm();
    }

    private static void initUm() {
        UMConfigure.init(context, "5da6ced93fc1952721000571", "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
        PlatformConfig.setWeixin("wxb4774b63d65a5718", "ee344a3c62a6fd69f512d462bc82bf50");
        PlatformConfig.setWXFileProvider("com.scoy.honeymei.fileprovider");

      //  UMConfigure.setLogEnabled(true);

    }

    private static void initJpush() {
        JPushInterface.init(context);
        JPushInterface.setDebugMode(false);
        //    JPushInterface.deleteAlias(this, 0);
        //   JPushInterface.stopPush(this);
    }

    //okgo初始化
    private void initOkgo() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        //   ** 屏蔽该行不打印信息  **          添加OkGo默认debug日志
     //   builder.addInterceptor(loggingInterceptor);

        //超时时间设置，默认60秒
        //全局的读取超时时间
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //全局的连接超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //自动管理cookie（或者叫session的保持），以下几种任选其一就行
        //使用数据库保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));

        OkGo.getInstance()
                //必须调用初始化
                .init(this)
                //建议设置OkHttpClient，不设置会使用默认的
                .setOkHttpClient(builder.build())
                //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheMode(CacheMode.NO_CACHE)
                //全局统一缓存时间，默认永不过期，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
                .setRetryCount(3);

    }


/*    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }*/

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorMainBlue, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }


}
